#include <vector>
#include <string.h>
#include <algorithm>

using namespace std;

class Solution
{
public:
    vector<int> relativeSortArray(vector<int> &arr1, vector<int> &arr2)
    {
        vector<int> ret;
        int tmp[1001];
        memset(tmp, 0, sizeof tmp);
        for (int i = 0; i < arr1.size(); ++i)
        {
            ++tmp[arr1[i]];
        }

        for (int i = 0; i < arr2.size(); ++i)
        {
            while (tmp[arr2[i]])
            {
                ret.push_back(arr2[i]);
                --tmp[arr2[i]];
            }
        }

        for (int i = 0; i < 1001; ++i)
        {
            while (tmp[i])
            {
                ret.push_back(i);
                tmp[i]--;
            }
        }
        return ret;
    }
};